const Task = require('../models/task')
const User = require('../models/user')
const Category = require('../models/category')
const Journal = require('../models/journal')
const Taskaudit = require('../models/taskaudit')
const response = require('../utils/response')
const loop = require('../utils/loop')
const fs = require('fs')
let path = require('path')
const {
    journal,
} = require('../validator/task')

const {
    deletaTask,
    countProcess,
    huanTime
} = require('../utils/tool')


// 获取任务列表
exports.getTasks = async (req, res, next) => {
    try {
        var limitNumber = Number(req.query.limitNumber) || Number(5)
        var skipNumber = Number(req.query.skipNumber) || Number(0)
        var task = await Task.find({
                grade: 0
            })
            .populate('worker', ['name'])
            .populate('creator', ['name'])
            .populate('parentId', ['taskname'])
            .sort({
                _id: -1
            })
            .skip(skipNumber) //跳过前sortNumber文档
            .limit(limitNumber) //查询后面的limitNumber个文档
            .lean()

        //查询上传文件人
        // for (let i in task) {
        //     for (let a in task[i].fileAddress) {
        //         let arr = task[i].fileAddress[a]
        //         if (arr.userId) {
        //             let user = await User.findById(arr.userId)
        //             arr.user = user
        //         }
        //     }
        // }

        await loop.deanTasks(task)
        const taskCount = await Task.countDocuments()
        const taskStatusCount0 = await Task.find({
            status: 0
        }).countDocuments()
        const taskStatusCount1 = await Task.find({
            status: 1
        }).countDocuments()
        const taskStatusCount2 = await Task.find({
            status: 2
        }).countDocuments()
        response(res, 200, '成功', {
            task,
            taskCount,
            taskStatusCount0,
            taskStatusCount1,
            taskStatusCount2
        })
    } catch (err) {
        next(err)
    }
}


// 分解任务
exports.createTask = async (req, res, next) => {
    try {
        // const files = req.files
        // req.body.fileAddress = files
        var task = new Task(req.body)
        task.status = 0
        task.process = 0

        let taskOne = await Task.findById(req.body.parentId)
        task.grade = (taskOne.grade) + 1

        //更正时间
        task.endtime = huanTime(task.endtime)
        task.createdAt = huanTime(Date.now())
        task.updatedAt = huanTime(Date.now())

        await task.save()

        // req.oldData = {}
        req.newData = task
        req.operate = 2
        next()
        // response(res, 200, '成功', {
        //     task
        // })
    } catch (err) {
        next(err)
    }
}

// 获取任务
exports.getTask = async (req, res, next) => {
    try {
        var task = await Task.find({
                "_id": req.params.taskId,
            })
            .populate('worker', ['name'])
            .populate('creator', ['name'])
            .populate('parentId', ['taskname'])
            .lean()

        // //查询上传文件人
        // for (let i in task) {
        //     for (let a in task[i].fileAddress) {
        //         let arr = task[i].fileAddress[a]
        //         if (arr.userId) {
        //             let user = await User.findById(arr.userId)
        //             arr.user = user
        //         }
        //     }
        // }

        if (!task) {
            response(res, 404, '找不到该任务', task)
        }
        await loop.deanTask(task)
        response(res, 200, '成功', task)
    } catch (err) {
        next(err)
    }
}



// 更新任务
exports.updataTask = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const bodyTask = req.body
        // const journal = new Journal()
        const task = await Task.findById(taskId)
        if (!task) {
            return response(res, 404, '找不到该任务', task)
        }

        task.taskname = bodyTask.taskname || task.taskname //任务名称
        task.worker = bodyTask.worker || task.worker //执行人
        task.describe = bodyTask.describe || task.describe //任务描述
        task.endtime = huanTime(bodyTask.endtime) || task.endtime //结束时间
        task.updatedAt = huanTime(Date.now())
        // await task.save()
        // res.send(task)
        // return
        let oldData = await Task.findByIdAndUpdate(taskId, task)

        req.oldData = oldData
        req.newData = task
        req.operate = 1
        next()
        // response(res, 200, '成功', task)
    } catch (err) {
        next(err)
    }
}

// 删除任务
exports.deleteTask = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const model = await Task.findByIdAndDelete(taskId)
        //删除审核表里所属的顶级任务
        await Taskaudit.deleteMany({
            taskId
        })

        //删除该任务下的子任务
        await deletaTask(taskId)

        req.oldData = model
        // req.newData = {}
        req.operate = 3
        next()
        // response(res, 200, '删除成功')
    } catch (err) {
        next(err)
    }
}


// 删除单个文件
exports.deleteFile = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        var task = await Task.findById(taskId)
        if (!task) {
            return response(res, 404, '找不到该任务', task)
        }
        var filename = req.query.filename
        if (!filename) {
            response(res, 404, '找不到该文件')
        }
        for (var i in task.fileAddress) {
            var tasksplit = task.fileAddress[i].split('/')
            var taskfile = tasksplit.pop()
            if (filename == taskfile) {
                fs.unlink(task.fileAddress[i], (err) => {})
                task.fileAddress.splice(i, 1)
            }
        }
        const taskflie = new Task(task)
        await taskflie.save()
        response(res, 200, '删除成功', task)
    } catch (err) {
        next(err)
    }
}

// 删除多个文件
exports.deleteAllFile = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        var task = await Task.findById(taskId)
        if (!task) {
            return response(res, 404, '找不到该任务', task)
        }
        for (var i in task.fileAddress) {
            fs.unlink(task.fileAddress[i], (err) => {})
        }
        task.fileAddress = []
        const taskflie = new Task(task)
        await taskflie.save()
        response(res, 200, '删除成功', task)
    } catch (err) {
        next(err)
    }
}

// 下载
exports.download = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const task = await Task.find({
            _id: taskId
        })
        fileAddress = task[0].fileAddress
        response(res, 200, '下载', fileAddress)
    } catch (err) {
        next(err)
    }
}

// 职位
exports.position = async (req, res, next) => {
    try {
        const position = await Category.findOne({
            "name": "专业带头人"
        })
        const positions = await User.find({
            "position": position._id
        })

        response(res, 200, '成功', positions)

    } catch (err) {
        next(err)
    }
}

// 统计
exports.statistical = async (req, res, next) => {
    try {


        let tasks = await Task.find({
            grade: 0
        })
        // 过滤字段
        tasks = tasks.map(v => {
            return {
                _id: v._id,
                taskname: v.taskname,
            }
        })

        // 获取今年的天数
        function myDate(t) { //t 代表指定的参数
            if (t == null) {
                var Year = new Date().getFullYear(),
                    s = 0,
                    d; //获取当前年
                for (var i = 1; i < 13; i++) {
                    d = new Date(Year, i, 0); //获取某一个月的天数
                    s += d.getDate();
                };
                return s;
            } else if (t >= 1970) {
                var Year = new Date().getFullYear(),
                    s = 0,
                    d;
                for (var i = 1; i < 13; i++) {
                    d = new Date(t, i, 0);
                    s += d.getDate();
                };
                return s;
            } else {
                return "年份有误";
            }
        }


        let nowTime = Date.now() + 8 * 60 * 60 * 1000
        let firstYearTime = new Date(nowTime)
        firstYearTime.setMonth(0)
        firstYearTime.setDate(1)
        firstYearTime.setHours(8)
        firstYearTime.setMinutes(0)
        firstYearTime.setSeconds(0)
        firstYearTime.setMilliseconds(0);

        let endYearTimes = firstYearTime.getTime() + myDate() * 24 * 60 * 60 * 1000
        let endYearTime = new Date(endYearTimes)

        
        // 查询统计进度
        for (let i in tasks) {
            let journal = await Journal.find({
                taskId: tasks[i]._id,
                createdAt:{
                    $gte: firstYearTime,
                    $lt: endYearTime
                }
            }).lean()
            journal = journal.map(v => {
                let time = new Date(v.createdAt)
                let month = time.getMonth()
                let year = time.getFullYear()
                if (month === 0) {
                    month = 12
                }
                return {
                    _id: v._id,
                    process: v.newData[0].process,
                    month: year + '/' + month
                }
            })
            tasks[i].journal = journal
        }

        // 排序
        for (let a in tasks) {
            tasks[a].journal.sort(function (a, b) {
                let time1 = new Date(b.month)
                let time2 = new Date(a.month)
                return time1 < time2 ? 1 : -1
            })
        }
        //  tasks.sort(function (a, b) {
        //      return b.createTime < a.createTime ? 1 : -1
        //  })

        // res.send(tasks)
        response(res, 200, '获取统计成功~~', tasks)



    } catch (error) {
        next(error)
    }
}